/*
 * Hello Minecraft! Launcher.
 * Copyright (C) 2013  huangyuhui <huanghongxun2008@126.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see {http://www.gnu.org/licenses/}.
 */
package org.jackhuang.hmcl.ui;

import org.jackhuang.hmcl.util.ui.Page;
import javax.swing.table.DefaultTableModel;
import org.jackhuang.hmcl.api.ui.TopTabPage;
import org.jackhuang.hmcl.core.download.MinecraftRemoteVersions;
import org.jackhuang.hmcl.setting.Settings;
import org.jackhuang.hmcl.util.C;
import org.jackhuang.hmcl.util.ui.MessageBox;
import org.jackhuang.hmcl.util.StrUtils;
import org.jackhuang.hmcl.util.task.ProgressProviderListener;
import org.jackhuang.hmcl.util.task.Task;
import org.jackhuang.hmcl.util.task.TaskWindow;
import org.jackhuang.hmcl.util.ui.SwingUtils;

/**
 *
 * @author huangyuhui
 */
public class GameDownloadPanel extends Page implements ProgressProviderListener {

    GameSettingsPanel gsp;

    /**
     * Creates new form GameDownloadPanel
     */
    public GameDownloadPanel(GameSettingsPanel gsp) {
        initComponents();
        this.gsp = gsp;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnDownload = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstDownloads = new javax.swing.JTable();
        btnRefreshGameDownloads = new javax.swing.JButton();

        btnDownload.setText(C.i18n("ui.button.download")); // NOI18N
        btnDownload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownloadActionPerformed(evt);
            }
        });

        lstDownloads.setModel(SwingUtils.makeDefaultTableModel(new String[]{C.i18n("install.version"), C.i18n("install.release_time"), C.i18n("install.time"), C.i18n("install.type")},new Class[]{String.class, String.class, String.class, String.class}, new boolean[]{false, false, false, false}));
        lstDownloads.setToolTipText("");
        lstDownloads.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(lstDownloads);

        btnRefreshGameDownloads.setText(C.i18n("ui.button.refresh")); // NOI18N
        btnRefreshGameDownloads.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshGameDownloadsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnDownload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRefreshGameDownloads, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(btnRefreshGameDownloads)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnDownload))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadActionPerformed
        downloadMinecraft();
        gsp.refreshVersions();
    }//GEN-LAST:event_btnDownloadActionPerformed

    private void btnRefreshGameDownloadsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshGameDownloadsActionPerformed
        refreshDownloads();
    }//GEN-LAST:event_btnRefreshGameDownloadsActionPerformed

    public void refreshDownloads() {
        if (loading)
            return;
        loading = true;
        DefaultTableModel model = SwingUtils.clearDefaultTable(lstDownloads);
        model.addRow(new Object[] { C.i18n("message.loading"), "", "" });
        MinecraftRemoteVersions.refreshRomoteVersions(Settings.getLastProfile().service().getDownloadType())
                .reg((ver) -> model.addRow(new Object[] { ver.id, ver.releaseTime, ver.time,
            StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot") ? C.i18n("versions." + ver.type) : ver.type }))
                .regDone(SwingUtils.invokeLater(() -> {
                    loading = false;
                    lstDownloads.requestFocus();
                    if (model.getRowCount() > 0)
                        model.removeRow(0);
                })).setProgressProviderListener(this).runAsync();
    }
    
    boolean loading = false;

    @Override
    public void setProgress(Task task, int prog, int max) {
        DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel();
        if (model.getRowCount() > 0)
            model.setValueAt(C.i18n("message.loading") + " " + (prog < 0 ? "???" : Integer.toString(prog * 100 / max) + "%"), 0, 0);
    }

    @Override
    public void setStatus(Task task, String sta) {
    }

    @Override
    public void onProgressProviderDone(Task task) {
    }

    void downloadMinecraft() {
        if (lstDownloads.getSelectedRow() < 0) {
            MessageBox.show(C.i18n("gamedownload.not_refreshed"));
            return;
        }
        String id = (String) lstDownloads.getModel().getValueAt(lstDownloads.getSelectedRow(), 0);
        TaskWindow.factory().execute(Settings.getLastProfile().service().download().downloadMinecraft(id));
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDownload;
    private javax.swing.JButton btnRefreshGameDownloads;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable lstDownloads;
    // End of variables declaration//GEN-END:variables

    boolean refreshedDownloads = false;

    @Override
    public void onSelect(TopTabPage page) {
        super.onSelect(page);
        if (!refreshedDownloads) {
            refreshedDownloads = true;
            refreshDownloads();
        }
    }
}
